<template>
	<gradient-background>
		<custom-navbar :title="'合一个'" :show-logo="false"></custom-navbar>
		
		<view class="container">
			<!-- 主体内容 -->
			<scroll-view scroll-y class="main-content">
				<view class="content-padding">
					<!-- 标题区域 -->
					<view class="title-section">
						<view class="title-icon">🔮</view>
						<text class="main-title">遇事不决，数象为引</text>
						<text class="sub-title">基于传统智慧的现代解读</text>
						<view class="title-decoration"></view>
					</view>
					
					<!-- 快速起卦功能 -->
					<view class="quick-divination-section">
						<view class="quick-divination-card" @tap="quickDivination">
							<view class="quick-icon">✨</view>
							<view class="quick-title">快速起卦</view>
							<view class="quick-desc">立即分析今日整体运势</view>
						</view>
					</view>
					
					<!-- 起卦入口 -->
					<view class="divination-section">
						
						<view class="divination-cards">
							<view class="card-wrapper">
								<divination-card 
									icon="⏰" 
									title="时间起卦" 
									type="time"
									@tap="navigateToTime"
								></divination-card>
							</view>
							<view class="card-wrapper">
								<divination-card 
									icon="🔢" 
									title="数字起卦" 
									type="number"
									@tap="navigateToNumber"
								></divination-card>
							</view>
						</view>
					</view>
					
					<!-- 今日卦签 -->
					<app-card :clickable="true" @tap="viewTodayHexagram" v-if="todayHexagram">
						<view class="today-hexagram">
							<view class="today-header">
								<text class="today-title">今日卦签</text>
								<text class="today-date">{{ todayDate }}</text>
							</view>
							<view class="hexagram-info">
								<view class="hexagram-symbol">
									<text class="symbol-text">{{ todayHexagram.fullSymbol }}</text>
								</view>
								<view class="hexagram-details">
									<text class="hexagram-name">{{ todayHexagram.name }}</text>
									<text class="hexagram-desc">{{ todayHexagram.description }}</text>
								</view>
							</view>
						</view>
					</app-card>
									
					<!-- 今日卦签加载中或错误状态 -->
					<app-card v-else>
						<view class="today-hexagram-loading">
							<view class="loading-content" v-if="loading">
								<text class="loading-text">今日卦签加载中...</text>
							</view>
							<view class="error-content" v-else>
								<text class="error-text">今日卦签加载失败</text>
							</view>
						</view>
					</app-card>
				</view>
			</scroll-view>
		</view>
	</gradient-background>
</template>

<script>
import GradientBackground from '@/components/gradient-background/gradient-background.vue'
import CustomNavbar from '@/components/custom-navbar/custom-navbar.vue'
import DivinationCard from '@/components/divination-card/divination-card.vue'
import AppCard from '@/components/app-card/app-card.vue'
import { HexagramService, Hexagram } from '@/utils/hexagram-service.js'
import apiService from '@/utils/api-service.js'
import { LoginService } from '@/utils/login-service.js'

export default {
	name: 'IndexPage',
	components: {
		GradientBackground,
		CustomNavbar,
		DivinationCard,
		AppCard
	},
	data() {
		return {
			todayHexagram: null,
			hexagramService: null,
			navigating: false, // 防止重复导航
			loading: true, // 加载状态
			loginService: null
		}
	},
	computed: {
		todayDate() {
			const today = new Date();
			const month = String(today.getMonth() + 1).padStart(2, '0');
			const day = String(today.getDate()).padStart(2, '0');
			return `${month}月${day}日`;
		}
	},
	onLoad() {
		this.initData();
	},
	methods: {
		initData() {
			console.log('Index - initData start');
			
			try {
				this.hexagramService = new HexagramService();
				this.loginService = new LoginService();
				console.log('Index - HexagramService created');
				
				// 使用后端API获取今日卦签
				this.loadTodayHexagram();
			} catch (error) {
				console.error('Index - initData error:', error);
				this.loading = false;
				uni.showToast({
					title: '初始化失败',
					icon: 'none'
				});
			}
		},
		
		/**
		 * 加载今日卦签
		 */
		async loadTodayHexagram() {
			this.loading = true;
			
			try {
				// 检查网络状态
				const isNetworkAvailable = await apiService.checkNetworkStatus();
				if (!isNetworkAvailable) {
					// 网络不可用时使用本地生成
					console.log('Index - 网络不可用，使用本地生成');
					this.todayHexagram = this.hexagramService.generateFromTime(new Date());
					this.loading = false;
					return;
				}
				
				// 调用后端API获取今日卦签
				const response = await apiService.timeDivination({
					question: '今日运势',
					useCurrentTime: true
				});
				
				console.log('Index - API response:', response);
				
				if (response.success && response.data && response.data.hexagram) {
					const hexagramData = response.data.hexagram;
					this.todayHexagram = new Hexagram({
						name: hexagramData.name,
						upperSymbol: hexagramData.upperTrigram?.symbol || '',
						lowerSymbol: hexagramData.lowerTrigram?.symbol || '',
						description: hexagramData.hexagramText || '',
						upperElement: hexagramData.upperTrigram?.element || '',
						lowerElement: hexagramData.lowerTrigram?.element || ''
					});
				} else {
					// API调用失败时使用本地生成
					console.log('Index - API调用失败，使用本地生成');
					this.todayHexagram = this.hexagramService.generateFromTime(new Date());
				}
			} catch (error) {
				console.error('Index - loadTodayHexagram error:', error);
				// 出现错误时使用本地生成
				this.todayHexagram = this.hexagramService.generateFromTime(new Date());
			} finally {
				this.loading = false;
				
				if (!this.todayHexagram) {
					console.error('Index - todayHexagram is null');
					uni.showToast({
						title: '今日卦签生成失败',
						icon: 'none'
					});
				}
			}
		},
		
		navigateToTime() {
			if (this.navigating) return;
			
			// 检查登录状态
			if (!this.loginService.isLoggedIn()) {
				uni.navigateTo({
					url: '/pages/login/new-login'
				});
				return;
			}
			
			this.navigating = true;
			uni.navigateTo({
				url: '/pages/time-divination/time-divination',
				complete: () => {
					setTimeout(() => {
						this.navigating = false;
					}, 1000);
				}
			});
		},
		
		navigateToNumber() {
			if (this.navigating) return;
			
			// 检查登录状态
			if (!this.loginService.isLoggedIn()) {
				uni.navigateTo({
					url: '/pages/login/new-login'
				});
				return;
			}
			
			this.navigating = true;
			uni.navigateTo({
				url: '/pages/number-divination/number-divination',
				complete: () => {
					setTimeout(() => {
						this.navigating = false;
					}, 1000);
				}
			});
		},
		
		async quickDivination() {
			if (this.navigating) return;
			
			// 检查登录状态
			if (!this.loginService.isLoggedIn()) {
				uni.navigateTo({
					url: '/pages/login/new-login'
				});
				return;
			}
			
			this.navigating = true;
			
			try {
				// 检查网络状态
				const isNetworkAvailable = await apiService.checkNetworkStatus();
				if (!isNetworkAvailable) {
					uni.showToast({
						title: '网络连接不可用',
						icon: 'none'
					});
					this.navigating = false;
					return;
				}
				
				uni.showLoading({
					title: '正在起卦...'
				});
				
				// 调用后端API进行快速起卦
				const response = await apiService.timeDivination({
					question: '今日整体运势',
					useCurrentTime: true
				});
				
				uni.hideLoading();
				
				if (response.success && response.data) {
					uni.navigateTo({
						url: `/pages/divination-result/divination-result?type=quick&question=今日整体运势&result=${encodeURIComponent(JSON.stringify(response.data))}`,
						complete: () => {
							setTimeout(() => {
								this.navigating = false;
							}, 1000);
						}
					});
				} else {
					uni.showToast({
						title: response.message || '快速起卦失败',
						icon: 'none'
					});
					this.navigating = false;
				}
			} catch (error) {
				console.error('Quick divination error:', error);
				uni.hideLoading();
				uni.showToast({
					title: '快速起卦失败',
					icon: 'none'
				});
				this.navigating = false;
			}
		},
		
		viewTodayHexagram() {
			if (!this.todayHexagram) {
				uni.showToast({
					title: '今日卦签数据不存在',
					icon: 'none'
				});
				return;
			}
			
			if (this.navigating) return;
			this.navigating = true;
			
			uni.navigateTo({
				url: `/pages/divination-result/divination-result?type=time&question=今日运势&hexagram=${encodeURIComponent(JSON.stringify(this.todayHexagram.toObject()))}`,
				complete: () => {
					setTimeout(() => {
						this.navigating = false;
					}, 1000);
				}
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.main-content {
	flex: 1;
	height: calc(100vh - 132rpx - 44px); /* 减去导航栏和TabBar高度 */
}

.content-padding {
	padding: 32rpx 48rpx 48rpx;
}

.title-section {
	text-align: center;
	margin-bottom: 80rpx;
	position: relative;
	
	.title-icon {
		font-size: 88rpx;
		margin-bottom: 24rpx;
		display: block;
		animation: float 3s ease-in-out infinite;
	}
	
	.main-title {
		display: block;
		font-size: 56rpx;
		font-weight: bold;
		color: #000000;
		margin-bottom: 16rpx;
		letter-spacing: 3rpx;
		text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
		background-clip: text;
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
	}
	
	.sub-title {
		display: block;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.7);
		line-height: 1.5;
		margin-bottom: 32rpx;
		font-weight: 300;
	}
	
	.title-decoration {
		width: 120rpx;
		height: 4rpx;
		background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
		margin: 0 auto;
		border-radius: 2rpx;
		box-shadow: 0 2rpx 12rpx rgba(106, 130, 251, 0.3);
	}
}

.quick-divination-section {
	margin-bottom: 48rpx;
	
	.quick-divination-card {
		background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
		border-radius: 32rpx;
		padding: 48rpx 32rpx;
		text-align: center;
		box-shadow: 0 8rpx 32rpx rgba(106, 130, 251, 0.3);
		transition: transform 0.3s ease, box-shadow 0.3s ease;
		
		&:active {
			transform: scale(0.98);
			box-shadow: 0 4rpx 16rpx rgba(106, 130, 251, 0.2);
		}
		
		.quick-icon {
			font-size: 88rpx;
			margin-bottom: 24rpx;
			display: block;
			animation: pulse 2s ease-in-out infinite;
		}
		
		.quick-title {
			display: block;
			font-size: 48rpx;
			font-weight: bold;
			color: #ffffff;
			margin-bottom: 16rpx;
			text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
		}
		
		.quick-desc {
			display: block;
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.9);
			font-weight: 300;
		}
	}
}

.divination-section {
	margin-bottom: 64rpx;
	
	.section-title {
		text-align: center;
		margin-bottom: 48rpx;
		
		.title-text {
			display: block;
			font-size: 40rpx;
			font-weight: 600;
			color: #000000;
			margin-bottom: 16rpx;
			position: relative;
			
			&::before {
				content: '✨';
				position: absolute;
				left: -48rpx;
				top: 50%;
				transform: translateY(-50%);
				font-size: 28rpx;
			}
			
			&::after {
				content: '✨';
				position: absolute;
				right: -48rpx;
				top: 50%;
				transform: translateY(-50%);
				font-size: 28rpx;
			}
		}
		
		.title-desc {
			display: block;
			font-size: 28rpx;
			color: rgba(0, 0, 0, 0.6);
			font-weight: 300;
		}
	}
	
	.divination-cards {
		display: flex;
		flex-direction: row;
		gap: 24rpx;
		padding: 0 16rpx;
		
		.card-wrapper {
			flex: 1;
			transform: scale(1);
			transition: transform 0.3s ease;
			
			&:active {
				transform: scale(0.98);
			}
		}
	}
}

.today-hexagram {
	position: relative;
	overflow: hidden;
	
	&::before {
		content: '';
		position: absolute;
		top: 0;
		right: 0;
		width: 160rpx;
		height: 160rpx;
		background: linear-gradient(135deg, rgba(106, 130, 251, 0.08) 0%, rgba(252, 92, 125, 0.08) 100%);
		border-radius: 50%;
		transform: translate(40rpx, -40rpx);
	}
	
	.today-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 32rpx;
		position: relative;
		z-index: 1;
		
		.today-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #000000;
			position: relative;
			
			&::before {
				content: '📅';
				margin-right: 12rpx;
			}
		}
		
		.today-date {
			font-size: 28rpx;
			color: rgba(0, 0, 0, 0.7);
			background: linear-gradient(135deg, #6A82FB 0%, #FC5C7D 100%);
			background-clip: text;
			-webkit-background-clip: text;
			-webkit-text-fill-color: transparent;
			font-weight: 500;
		}
	}
	
	.hexagram-info {
		display: flex;
		align-items: center;
		position: relative;
		z-index: 1;
		
		.hexagram-symbol {
			margin-right: 32rpx;
			background: linear-gradient(135deg, rgba(106, 130, 251, 0.1) 0%, rgba(252, 92, 125, 0.1) 100%);
			border-radius: 24rpx;
			padding: 16rpx;
			box-shadow: 0 4rpx 16rpx rgba(106, 130, 251, 0.1);
			
			.symbol-text {
				font-size: 72rpx;
				line-height: 1;
				display: block;
			}
		}
		
		.hexagram-details {
			flex: 1;
			
			.hexagram-name {
				display: block;
				font-size: 36rpx;
				font-weight: 600;
				color: #000000;
				margin-bottom: 12rpx;
				line-height: 1.3;
			}
			
			.hexagram-desc {
				display: block;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.7);
				line-height: 1.5;
				font-weight: 300;
			}
		}
	}
}

.today-hexagram-loading {
	.loading-content, .error-content {
		text-align: center;
		padding: 60rpx 0;
		
		.loading-text, .error-text {
			font-size: 28rpx;
			color: rgba(0, 0, 0, 0.7);
			position: relative;
			
			&::after {
				content: '';
				display: inline-block;
				width: 20rpx;
				height: 20rpx;
				border: 2rpx solid #6A82FB;
				border-radius: 50%;
				border-top-color: transparent;
				animation: spin 1s linear infinite;
				margin-left: 16rpx;
			}
		}
		
		.error-text {
			&::after {
				display: none;
			}
		}
	}
}

/* 动画效果 */
@keyframes float {
	0%, 100% {
		transform: translateY(0);
	}
	50% {
		transform: translateY(-10rpx);
	}
}

@keyframes spin {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

@keyframes pulse {
	0%, 100% {
		transform: scale(1);
	}
	50% {
		transform: scale(1.1);
	}
}
</style>